<template>
  <div class="app-container">
    <el-card>
      <el-form
          :model="queryParams"
          ref="queryRef"
          :inline="true"
          v-show="showSearch"
      >

        <el-form-item label="评估机构">
          <el-select
              v-model="queryParams.evaluationAgencyId"
              clearable
              filterable
              placeholder="请选择评估机构"
              style="width: 240px"
          >
                        <el-option
                            v-for="dict in communitySiteList"
                            :key="dict.id"
                            :label="dict.name"
                            :value="dict.id"
                        ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="人员名称">
          <el-input
              v-model="queryParams.name"
              placeholder="请输入人员名称"
              clearable
              @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="状态">
          <el-select
              v-model="queryParams.status"
              clearable
              placeholder="请选择状态"
              style="width: 240px"
          >
                        <el-option
                            v-for="dict in contract_status"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                        ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="addDeviceTypes"
          >新增</el-button
          >
        </el-col>

        <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getList"
        ></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="postList" stripe border max-height="500">
        <el-table-column label="评估机构" align="center" prop="evaluationAgencyName" />
        <el-table-column label="人员姓名" align="center" prop="name" />
        <el-table-column label="岗位" align="center" width="400" show-overflow-tooltip>
          <template #default="scope">
            <span>{{scope.row.positionList.map(item => item.positionName)?.join(',')}}</span>
          </template>
        </el-table-column>
        <el-table-column label="性别" align="center" prop="postCode" >
          <template #default="scope">
        <span>
          {{sys_user_sex.find(item=>item.value==scope.row.sex)? sys_user_sex.find(item=>item.value==scope.row.sex).label:''}}

        </span>
          </template>
        </el-table-column>
        <el-table-column label="手机号（登录账号）" align="center" prop="phone" />
        <el-table-column label="状态" align="center" >
          <template #default="scope">

            <el-tag :type="scope.row.status === '1' ? '':'danger'">
                <span>
               {{contract_status.find(item=>item.value==scope.row.status)? contract_status.find(item=>item.value==scope.row.status).label:''}}
            </span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="notes" />
        <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button link type="primary"  @click="edit(scope.row)"
            >修改</el-button
            >

            <el-button
                link
                type="danger"

                @click="handleDelete(scope.row)"
            >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.page"
          v-model:limit="queryParams.limit"
          @pagination="getList"
      />
    </el-card>
    <el-dialog
        v-model="open"
        :title="title"
        append-to-body
        width="800px"
        v-if="open"
        @close="cancel"
        :close-on-click-modal="false"
    >
      <el-form
          ref="assessPeopleRef"
          :model="form"
          :rules="rules"
          label-width="150px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="评估机构" prop="evaluationAgencyId" >
              <el-select
                  :disabled="form.id?true:false"
                  v-model="form.evaluationAgencyId"
                  clearable
                  filterable
                  placeholder="请选择站点名称"
                  style="width:100%"
              >
                <el-option
                    v-for="dict in communitySiteList"
                    :key="dict.id"
                    :label="dict.name"
                    :value="dict.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="人员姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入联系人"  :disabled="form.id?true:false" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号（登录账号）" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话"  :disabled="form.id?true:false" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
          <el-form-item label="性别" prop="sex">
            <el-select v-model="form.sex" clearable  placeholder="请选择性别" style="width: 100%">
              <el-option
                  v-for="dict in sys_user_sex"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          </el-col>
          <el-col :span="24">
          <el-form-item label="岗位" >
            <el-select v-model="positionList" multiple clearable placeholder="请选择岗位" style="width: 100%">
              <el-option
                  v-for="dict in PositionListData"
                  :key="dict.positionId"
                  :label="dict.positionName"
                  :value="dict.positionId">
                         <span>{{dict.positionDeptName}}</span>
              </el-option>
            </el-select>
          </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="状态" >
              <el-radio-group v-model="form.status">
                            <el-radio
                                v-for="(item, index) in contract_status"
                                :key="index"
                                :label="item.value"
                            >{{ item.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="notes">
              <el-input
                  v-model="form.notes"
                  show-word-limit
                  maxlength="500"
                  type="textarea"
                  :autosize="{ minRows: 2, maxRows: 8 }"
                  placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormDebounceHandler"
          >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改岗位对话框 -->
  </div>
</template>

<script setup name="communitySitePeople">

const { proxy } = getCurrentInstance();
const { sys_normal_disable, sys_user_sex, device_category,contract_status } = proxy.useDict(
    "sys_normal_disable",
    "sys_user_sex",
    "device_category",
    'contract_status'
);
import {
getPositionList
} from "@/api/homeBed/index";

import { debounce } from "@/utils/debounce.js";

import {  getAssessPeopleData,
  getAssessOrganizationData,
  addNewAssessPeopleData,
  editAssessPeopleData,
  deleteAssessPeopleData } from "@/api/assessOrganization"
const route = useRoute();
const showSearch = ref(true);
const loading = ref(true);
const postList = ref([]);
const open = ref(false);
const routeValue=ref(null);
const title = ref("新增站点人员");
const communitySiteList=ref([]);
const PositionListData=ref([]);
const positionList=ref([]);
const total = ref(0);

const data = reactive({
  form: {
    status:'1'
  },
  queryParams: {
    page: 1,
    limit: 10,
    status: undefined,
    name:undefined,
    evaluationAgencyId:undefined
  },
  rules: {
    evaluationAgencyId: [
      { required: true, message: "请选择评估机构", trigger: "change" },
    ],
    name: [
      { required: true, message: "请输入人员姓名", trigger: "blur" },
      { required: true, min: 1, max: 10, message: "人员姓名不超过10个字符", trigger: "blur" }
    ],
    phone:[
      { required: true, message: "请输入正确手机号", trigger: "blur"},
      { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur"}
    ],
    sex: [
      { required: true, message: "请选择性别", trigger: "change" },
    ],
    notes: [
      { required: false, message: "请输入备注信息", trigger: "blur" },
      { required: false, min: 1, max: 10, message: "备注不超过500个字符", trigger: "blur" }
    ]
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 提交按钮 */
const submitFormDebounceHandler = debounce(submitForm, 500);
function submitForm() {
  proxy.$refs["assessPeopleRef"].validate((valid) => {
    if (valid) {
      form.value.evaluationAgencyName=communitySiteList.value.find(item=>item.id==form.value.evaluationAgencyId)?.name

      form.value.positionList=filterArrayByPositionId(PositionListData.value,positionList.value)
      console.log('22222222222',form.value.positionList)

      if (form.value.id != undefined) {
        editAssessPeopleData(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          reset();
          getList();
        });
      } else {
        addNewAssessPeopleData(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          reset();
          getList();
        });
      }
    }
  });
}

function cancel() {
  open.value = false;
  reset();
}
function edit(data) {


  form.value = data;
  for(let i in data.positionList){
    positionList.value.push(data.positionList[i].positionId)
  }
  title.value = "编辑站点人员";
  open.value = true;
}
function reset() {
  form.value = {
    id: null,
    sex:null,
    evaluationAgencyId:routeValue.value-0,
    evaluationAgencyName:null,
    name:null,
    phone:null,
    status:'1',
    positionList:[],
    notes:''
  };
  positionList.value=[]
  proxy.resetForm("assessPeopleRef");
}
/** 查询岗位列表 */
function getList() {
  loading.value = true;
  getAssessPeopleData(queryParams.value).then((response) => {
    postList.value = response.page.list;
    total.value = response.page.totalCount;
    loading.value = false;
  });
}
function filterArrayByPositionId(arr, selectedPositionIds) {
  return arr.filter(item => selectedPositionIds.includes(item.positionId));
}
function PositionList(){
  getPositionList().then(res=>{
    PositionListData.value=res.rows

  })
}
function handleQuery() {
  getList();
}
function resetQuery() {
  queryParams.value = {
    page: 1,
    limit: 10,
    status: undefined,
    name:undefined,
    evaluationAgencyId: null
  };
  getList();
}

function handleDelete(row) {
  console.log(row);

  proxy.$modal
      .confirm("是否确认删除该数据项？")
      .then(function () {
        return deleteAssessPeopleData([row.id]);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
      })
      .catch(() => {});
}
function addDeviceTypes() {
  title.value = "新增站点人员";
  open.value = true;
}

function getCommunitySite(){
  let obj={
    page: 1,
    limit: 999,
  }
  getAssessOrganizationData(obj).then(res=>{
    communitySiteList.value=res.page.list;
  })
}



const stopWatch = watch(
    () => route,
    (newVal, oldVal) => {
      routeValue.value = newVal.params.id;
      queryParams.value.evaluationAgencyId=newVal.params.id-0
      form.value.evaluationAgencyId=newVal.params.id-0
    },
    { immediate: true }
);

onBeforeUnmount(() => {
  stopWatch();
});

getList();
getCommunitySite()
PositionList()
</script>
